import os import random import pygame import tkinter as tk # Paths AUDIO_PATH = r"C:\Users\Admin\PycharmProjects\PythonProject1\Alphabets\Audioalphabet" FEEDBACK_AUDIO_PATH = r"C:\Users\Admin\PycharmProjects\PythonProject1\Audio" # Initialize pygame mixer pygame.mixer.init() class AudioQuizApp: def __init__(self, root): self.root = root self.root.title("Audio Quiz") self.root.geometry("400x300") self.question_label = tk.Label(root, text="Listen to the audio and choose the correct option:", font=("Arial", 12)) self.question_label.pack(pady=10) self.options_frame = tk.Frame(root) self.options_frame.pack(pady=10) self.buttons = [] for i in range(4): btn = tk.Button(self.options_frame, text="", font=("Arial", 12), width=20, command=lambda i=i: self.check_answer(i)) btn.pack(pady=5) self.buttons.append(btn) self.next_button = tk.Button(root, text="Next Question", font=("Arial", 12), command=self.load_question) self.next_button.pack(pady=10) self.correct_file = None self.correct_answer = None self.options = [] self.load_question() def play_audio(self, file_path): """Play an audio file using Sound() for better control.""" if os.path.exists(file_path): sound = pygame.mixer.Sound(file_path) sound.play() else: print(f"Audio file not found: {file_path}") # Removed pop-up, now prints error def get_audio_files(self): """Get list of available audio quiz files.""" return [f for f in os.listdir(AUDIO_PATH) if f.endswith(".mp3") or f.endswith(".wav")] def load_question(self): """Load a new question and play the corresponding audio automatically.""" audio_files = self.get_audio_files() if len(audio_files) < 4: print("Error: Not enough audio files for a quiz.") # Removed pop-up, now prints error return self.correct_file = random.choice(audio_files) self.correct_answer = os.path.splitext(self.correct_file)[0] self.options = random.sample(audio_files, 3) if self.correct_file not in self.options: self.options.append(self.correct_file) else: self.options = random.sample(audio_files, 4) self.options = [os.path.splitext(opt)[0] for opt in self.options] random.shuffle(self.options) for i, option in enumerate(self.options): self.buttons[i].config(text=option) # Automatically play the quiz audio self.play_audio(os.path.join(AUDIO_PATH, self.correct_file)) def check_answer(self, index): """Check if the selected answer is correct and play feedback audio.""" selected_option = self.options[index] if selected_option == self.correct_answer: feedback_file = os.path.join(FEEDBACK_AUDIO_PATH, "Rightanswer.mp3") else: feedback_file = os.path.join(FEEDBACK_AUDIO_PATH, "Wronganswer.mp3") # Play feedback audio using Sound() self.play_audio(feedback_file) # Load the next question after a short delay to ensure feedback audio plays self.root.after(2000, self.load_question) # Run the application if __name__ == "__main__": root = tk.Tk() app = AudioQuizApp(root) root.mainloop()